import React from "react";
import { Table, Button } from "antd";
import { connect } from 'react-redux'
import { createColumns } from "./config";
import { getTableData, deleteStudent } from "./sevice";

export class List extends React.Component {
  // didmount后请求下数据
  componentDidMount() {
    this.getTableData(this.props.current);
  }
  // 获取列表数据，更新state
  getTableData = (current) => {
    getTableData({
      pageNo: current,
      pageSize: 10,
      classId: "2113",
    }).then((res) => {
      if (!res) {
        return;
      }
      const { result = {} } = res;
      const { data = [], total } = result;
      this.props.dispatch({
        type: "UPDATE",
        params: {
           dataSource: data,
            total,
        }
      })
    });
  };
  // 删除某一项，重新请求本页数据
  deleteStudent = (id) => {
    deleteStudent({
      id,
    }).then((res) => {
      if (!res) {
        return;
      }
      this.getTableData(this.props.current);
    });
  };

  render() {
    console.log(this.props);
    const { dataSource, total, current } = this.props;
    const columns = createColumns({
      deleteStudent: this.deleteStudent,
    });
    return (
      <div>
        <div>
          <Button type="primary">添加学员</Button>
        </div>
        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          pagination={{
            total,
            current,
            pageSize: 10,
            showSizeChanger: false,
            onChange: (page) => {
              this.props.dispatch({
                action: 'UPDATE',
                params: {
                  current: page,
                },
              });
              this.getTableData(page);
            },
          }}
        />
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  const {dataSource, total, current} = state.listData || {};
  return {
    dataSource,
    total,
    current
  }
}
const mapDisPatchToProps = (dispatch) => {
  return {
    dispatch
  }
}


export default connect(mapStateToProps,mapDisPatchToProps)(List)